﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace ConsoleAppTestEf.Models
{
    public class BlogContext:DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("", (builder) => {
                //builder.
            });
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //创建表 指定属性 三种方式
            //1 DbSet
            //2 DataAnnotations
            //3 Fluent API

            //base.OnModelCreating(modelBuilder);

            //mark url property must be not null             
            modelBuilder.Entity<Blog>()
                .Property(b => b.Url)
                .IsRequired();

            //no Dbset create table
            modelBuilder.Entity<AuditEntity>();

            //忽略某个集合 不创建表   [NotMapped]
            modelBuilder.Ignore<MethEntity>();

            //生成默认值
            //DatabaseGenerated(DatabaseGeneratedOption.Identy)


            //Timestamp 存储为byte[] 可以作为ROWVERSION 

            //shade property 

            //index 索引 只能通过 FluentApi 创建
            modelBuilder.Entity<Blog>()
                .HasIndex(b => b.Url) 
                .IsUnique();

            //默认值 FluentAPI HasDefaultValueSql("")

            //类型转换  ef core 2.1增加
            //data seeding 种子数据 ef core 2.1 增加
        }
    }

    [NotMapped]
    internal class MethEntity
    {
    }

    public class AuditEntity
    {
        [Key]
        public int Id { get; set; }
        public string Username { get; set; }
        [Timestamp]
        public byte[] Timestamp { get; set; }
        public string Action { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        [Required]
        public string Url { get; set; }
        public int Rating { get; set; }
        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}
